<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代理名称" prop="proxyName">
        <el-input
          v-model="queryParams.proxyName"
          placeholder="请输入代理名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模式" prop="mode">
        <el-select v-model="queryParams.mode" placeholder="请选择模式" clearable>
          <el-option
            v-for="dict in dict.type.proxy_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lbconfig:frontproxy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lbconfig:frontproxy:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lbconfig:frontproxy:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleReload"
          v-hasPermi="['lbconfig:frontproxy:edit']"
        >重载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-warning"
          size="mini"
          @click="handleInfo"
          v-hasPermi="['lbconfig:frontproxy:list']"
        >提示</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="frontproxyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="标识ID" width="60" align="center" prop="id" />
      <el-table-column label="代理名称" align="center" prop="proxyName" />
      <el-table-column label="绑定设备" width="80" align="center" prop="bindDevice" v-if="cluster.mode=='MM'"/>
      <el-table-column label="绑定地址/端口" width="350" align="center" prop="bindIp" >
        <template slot-scope="scope">
          {{scope.row.bindIp.indexOf(":") > 0 ?"[" + scope.row.bindIp + "]:" + scope.row.bindPort : scope.row.bindIp + ":" + scope.row.bindPort}}
        </template>
      </el-table-column>
      <!-- <el-table-column label="绑定端口" align="center" prop="bindPort" /> -->
      <el-table-column label="模式" width="60" align="center" prop="mode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.proxy_mode" :value="scope.row.mode"/>
        </template>
      </el-table-column>
      <el-table-column label="调度算法" align="center" prop="balance">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.proxy_balance" :value="scope.row.balance"/>
        </template>
      </el-table-column>
      <el-table-column label="健康检测方式" align="center" prop="healthCheck">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.proxy_health_check" :value="scope.row.healthCheck"/>
        </template>
      </el-table-column>

      <el-table-column label="SSL卸载" width="80" align="center" prop="sslOffloading">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.sslOffloading == 1">开启</el-tag>
          <el-tag type="danger" v-if="scope.row.sslOffloading == 0">关闭</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="60" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0" @change="changeProxyStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['lbconfig:frontproxy:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            @click="handleCheck(scope.row)"
            v-hasPermi="['lbconfig:frontproxy:edit']"
          >检测</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['lbconfig:frontproxy:remove']"
          >删除</el-button> -->

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['lbconfig:frontproxy:remove','lbconfig:frontproxy:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleCheck" icon="el-icon-s-check" 
                v-hasPermi="['lbconfig:frontproxy:edit']">检测</el-dropdown-item>
              <el-dropdown-item command="handleDelete" icon="el-icon-delete" 
                v-hasPermi="['lbconfig:frontproxy:remove']">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 检测前端代理配置对话框 -->
    <el-dialog title="前端代理配置检测" :visible.sync="checkOpen" width="700px" height="400px" append-to-body>
      <pre v-text="configCheckResult" id="checkResult">

      </pre>
        
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listFrontproxy, delFrontproxy, changeProxyStatus, checkFrontproxy, getCluster, reloadProxy } from "@/api/lbconfig/frontproxy";

export default {
  name: "Frontproxy",
  dicts: ['proxy_mode', 'proxy_health_check', 'proxy_balance'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 唯一标识符
      uniqueId: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 前端代理表格数据
      frontproxyList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        proxyName: null,
        mode: null,
      },
      // 表单参数
      form: {},
      // 配置同步表单
      syncForm: {},
      // 表单校验
      syncRules: {
        syncSeqid: [
          { required: true, message: "同步序列不能为空", trigger: "blur" }
        ],
        srcAddr: [
          { required: true, message: "同步源地址不能为空", trigger: "blur" }
        ],
        dstAddr: [
          { required: true, message: "同步目的地址不能为空", trigger: "blur" }
        ],
      },
      syncOpen: false,
      configCheckResult: null,
      checkOpen: false,
      cluster:[]
    };
  },
  created() {
    // this.getList();
    
    getCluster().then(response => {
      this.cluster = response.data;
    });
  },
  activated() {
    // const time = this.$route.query.t;
    // if (time != null && time != this.uniqueId) {
    //   this.uniqueId = time;
    //   this.queryParams.pageNum = Number(this.$route.query.pageNum);
    //   this.getList();
    // }
    this.getList();
  },
  methods: {
    /** 查询前端代理列表 */
    getList() {
      this.loading = true;
      listFrontproxy(this.queryParams).then(response => {
        this.frontproxyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {      
      this.$tab.openPage("前端代理配置", '/lbconfig/frontproxy-edit/index');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const proxyId = row.id || this.ids[0];
      const proxyName = row.proxyName;
      const params = { pageNum: this.queryParams.pageNum };
      console.log(proxyId + "  :  " + proxyName);
      // this.$tab.openPage("修改[" + proxyName + "]代理配置", '/lbconfig/frontproxy-edit/index/' + proxyId, params);
      this.$tab.openPage("前端代理配置", '/lbconfig/frontproxy-edit/index', {proxyId:proxyId, pageNum: this.queryParams.pageNum});

      // this.$router.push({path:'/lbconfig/frontproxy-edit/index',query:{proxyId:proxyId, pageNum: this.queryParams.pageNum}});
    
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除前端代理编号为"' + ids + '"的数据项？').then(function() {
        return delFrontproxy(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lbconfig/frontproxy/export', {
        ...this.queryParams
      }, `frontproxy_${new Date().getTime()}.xlsx`)
    },
    handleInfo(){
      const h = this.$createElement;
      this.$msgbox({
          title: '提示',
          message: h('p', {style : 'color:red; font-size:small; font-weight:bold'}, [
            h('li', null, '1.请及时保持集群配置同步，以有效利用集群资源获取理想负载效果'),
            h('li', null, '2.在集群配置不同步场景下，为了保持功能运行正常，请集群各节点执行重载前端代理操作，否则可能引起前端代理失效'),
            h('li', null, '3.本界面【配置同步】按钮操作同【系统配置=>数据维护=>集群配置数据同步=>配置同步】'),
          ]),
          showCancelButton: false,
          confirmButtonText: '关闭',
          cancelButtonText: '取消',
        }).then(action => {
          
        }).catch(() => {
          
        });
    },
    handleReload(){
      reloadProxy().then(response => {
        // console.log(response);
        if (response.code === 200) {
          if(response.data && response.data.resultCode == "0"){
            this.$modal.msgError(response.data.msg);
          } else if(response.data && response.data.resultCode == "1"){
            this.$modal.msgSuccess(response.data.msg);
          } else {
            this.$modal.msgSuccess("重载策略成功");
          }
        } else {
          this.$modal.msgError("重载策略失败");
        }        
      });
    },
    changeProxyStatus(row) {
      // console.log(row);
      changeProxyStatus(row.id, row.status).then(response => {
        // console.log(response);
        if (response.code === 200) {
          if(response.data && response.data.resultCode == "0"){
            this.$modal.msgError(response.data.msg);
            //还原状态
            row.status = row.status == "0"?"1":"0";
          } else if(response.data && response.data.resultCode == "1"){
            this.$modal.msgSuccess(response.data.msg);
          } else this.$modal.msgSuccess("修改成功");
        } else {
          this.$modal.msgError("修改失败");
          //还原状态
          row.status = row.status == "0"?"1":"0";
        }        
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleCheck":
          this.handleCheck(row);
          break;
        default:
          break;
      }
    },
    /** 检测本策略配置是否正常 */
    handleCheck(row) {
      checkFrontproxy(row.id).then(response => {
        this.$modal.msgSuccess("检测完成");
        //console.log(response);
        this.configCheckResult = response.data.configCheckResult;
        this.checkOpen = true;
      });
    },
    cancel(){
      this.checkOpen = false;
      this.configCheckResult = "";
    },
  }
};
</script>

<style lang="less">
  #checkResult {
      display: block;
        padding: 9.5px;
      margin: 0 0 10px;
      font-size: 13px;
      line-height: 1.42857143;
      color: #333;
      word-break: break-all;
      word-wrap: break-word;
      background-color: #f5f5f5;
      border: 1px solid #ccc;
      border-radius: 4px;
      overflow: auto;
      min-height: 300px;
      max-height: 400px;
  }
</style>
